package com.it.hanzhongtravelv1.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/images")
@CrossOrigin(origins = "*")
public class ImageController {
    
    // 使用项目内部的静态资源路径
    private static final String IMAGE_BASE_PATH = initImagePath();
    private static final String WEB_BASE_PATH = "img/";
    
    /**
     * 初始化图片存储路径
     */
    private static String initImagePath() {
        // 指向 src/main/resources/static/img/
        // 注意：这种方式在开发环境中有效，但在打包成JAR文件后可能需要调整
        String projectRoot = System.getProperty("user.dir");
        String imagePath = projectRoot + File.separator + "src" + File.separator + "main" + 
                           File.separator + "resources" + File.separator + "static" + 
                           File.separator + "img" + File.separator;
        
        // 假设分类目录已在项目中创建好
        return imagePath;
    }
    
    /**
     * 创建默认分类目录 (现在不再需要，因为目录是项目的一部分)
     */
    private static void createDefaultCategories(String basePath) {
        // 这个方法现在可以留空或删除，因为目录已经存在于项目中
    }
    
    /**
     * 获取配置信息（调试用）
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("IMAGE_BASE_PATH", IMAGE_BASE_PATH);
        config.put("WEB_BASE_PATH", WEB_BASE_PATH);
        config.put("user.home", System.getProperty("user.home"));
        config.put("user.dir", System.getProperty("user.dir"));
        
        File baseDir = new File(IMAGE_BASE_PATH);
        config.put("baseDir.exists", baseDir.exists());
        config.put("baseDir.canWrite", baseDir.canWrite());
        config.put("baseDir.absolutePath", baseDir.getAbsolutePath());
        
        return ResponseEntity.ok(config);
    }
    
    /**
     * 获取所有图片分类
     */
    @GetMapping("/categories")
    public ResponseEntity<List<String>> getImageCategories() {
        try {
            File baseDir = new File(IMAGE_BASE_PATH);
            if (!baseDir.exists()) {
                return ResponseEntity.ok(new ArrayList<>());
            }
            
            List<String> categories = Arrays.stream(baseDir.listFiles())
                    .filter(File::isDirectory)
                    .map(File::getName)
                    .sorted()
                    .collect(Collectors.toList());
                    
            return ResponseEntity.ok(categories);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取指定分类下的所有图片
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<List<Map<String, Object>>> getImagesByCategory(@PathVariable String category) {
        try {
            File categoryDir = new File(IMAGE_BASE_PATH + category);
            if (!categoryDir.exists() || !categoryDir.isDirectory()) {
                return ResponseEntity.ok(new ArrayList<>());
            }
            
            List<Map<String, Object>> images = Arrays.stream(categoryDir.listFiles())
                    .filter(file -> file.isFile() && isImageFile(file.getName()))
                    .map(file -> {
                        Map<String, Object> imageInfo = new HashMap<>();
                        imageInfo.put("name", file.getName());
                        imageInfo.put("path", WEB_BASE_PATH + category + "/" + file.getName());
                        imageInfo.put("category", category);
                        imageInfo.put("size", file.length());
                        imageInfo.put("lastModified", file.lastModified());
                        return imageInfo;
                    })
                    .sorted((a, b) -> ((String) a.get("name")).compareTo((String) b.get("name")))
                    .collect(Collectors.toList());
                    
            return ResponseEntity.ok(images);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取所有图片（带分类信息）
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, List<Map<String, Object>>>> getAllImages() {
        try {
            File baseDir = new File(IMAGE_BASE_PATH);
            if (!baseDir.exists()) {
                return ResponseEntity.ok(new HashMap<>());
            }
            
            Map<String, List<Map<String, Object>>> allImages = new HashMap<>();
            
            Arrays.stream(baseDir.listFiles())
                    .filter(File::isDirectory)
                    .forEach(categoryDir -> {
                        String category = categoryDir.getName();
                        List<Map<String, Object>> images = Arrays.stream(categoryDir.listFiles())
                                .filter(file -> file.isFile() && isImageFile(file.getName()))
                                .map(file -> {
                                    Map<String, Object> imageInfo = new HashMap<>();
                                    imageInfo.put("name", file.getName());
                                    imageInfo.put("path", WEB_BASE_PATH + category + "/" + file.getName());
                                    imageInfo.put("category", category);
                                    imageInfo.put("size", file.length());
                                    imageInfo.put("lastModified", file.lastModified());
                                    return imageInfo;
                                })
                                .sorted((a, b) -> ((String) a.get("name")).compareTo((String) b.get("name")))
                                .collect(Collectors.toList());
                        
                        allImages.put(category, images);
                    });
                    
            return ResponseEntity.ok(allImages);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 上传图片到指定分类
     */
    @PostMapping("/upload/{category}")
    public ResponseEntity<Map<String, Object>> uploadImage(
            @PathVariable String category,
            @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "文件不能为空"));
            }
            
            if (!isImageFile(file.getOriginalFilename())) {
                return ResponseEntity.badRequest().body(Map.of("error", "只支持图片文件（jpg, jpeg, png, gif, webp）"));
            }
            
            // 创建目录（如果不存在）
            File categoryDir = new File(IMAGE_BASE_PATH + category);
            if (!categoryDir.exists()) {
                categoryDir.mkdirs();
            }
            
            // 保存文件
            String fileName = file.getOriginalFilename();
            File targetFile = new File(categoryDir, fileName);
            
            // 如果文件已存在，添加时间戳
            if (targetFile.exists()) {
                String nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
                String extension = fileName.substring(fileName.lastIndexOf('.'));
                fileName = nameWithoutExt + "_" + System.currentTimeMillis() + extension;
                targetFile = new File(categoryDir, fileName);
            }
            
            file.transferTo(targetFile);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "图片上传成功");
            result.put("name", fileName);
            result.put("path", WEB_BASE_PATH + category + "/" + fileName);
            result.put("size", targetFile.length());
            result.put("category", category);
            
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            return ResponseEntity.internalServerError().body(Map.of("error", "文件上传失败：" + e.getMessage()));
        }
    }
    
    /**
     * 删除图片
     */
    @DeleteMapping("/{category}/{filename}")
    public ResponseEntity<Map<String, Object>> deleteImage(
            @PathVariable String category,
            @PathVariable String filename) {
        try {
            File imageFile = new File(IMAGE_BASE_PATH + category + "/" + filename);
            
            if (!imageFile.exists()) {
                return ResponseEntity.notFound().build();
            }
            
            boolean deleted = imageFile.delete();
            
            if (deleted) {
                return ResponseEntity.ok(Map.of("success", true, "message", "图片删除成功"));
            } else {
                return ResponseEntity.internalServerError().body(Map.of("error", "图片删除失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of("error", "删除操作失败：" + e.getMessage()));
        }
    }
    
    /**
     * 创建新的图片分类
     */
    @PostMapping("/category/{category}")
    public ResponseEntity<Map<String, Object>> createCategory(@PathVariable String category) {
        try {
            File categoryDir = new File(IMAGE_BASE_PATH + category);
            
            if (categoryDir.exists()) {
                return ResponseEntity.badRequest().body(Map.of("error", "分类已存在"));
            }
            
            boolean created = categoryDir.mkdirs();
            
            if (created) {
                return ResponseEntity.ok(Map.of("success", true, "message", "分类创建成功"));
            } else {
                return ResponseEntity.internalServerError().body(Map.of("error", "分类创建失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of("error", "创建操作失败：" + e.getMessage()));
        }
    }
    
    /**
     * 删除图片分类（只有空分类才能删除）
     */
    @DeleteMapping("/category/{category}")
    public ResponseEntity<Map<String, Object>> deleteCategory(@PathVariable String category) {
        try {
            File categoryDir = new File(IMAGE_BASE_PATH + category);
            
            if (!categoryDir.exists()) {
                return ResponseEntity.notFound().build();
            }
            
            // 检查目录是否为空
            File[] files = categoryDir.listFiles();
            if (files != null && files.length > 0) {
                return ResponseEntity.badRequest().body(Map.of("error", "只能删除空的分类"));
            }
            
            boolean deleted = categoryDir.delete();
            
            if (deleted) {
                return ResponseEntity.ok(Map.of("success", true, "message", "分类删除成功"));
            } else {
                return ResponseEntity.internalServerError().body(Map.of("error", "分类删除失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of("error", "删除操作失败：" + e.getMessage()));
        }
    }
    
    /**
     * 重命名图片
     */
    @PutMapping("/{category}/{filename}")
    public ResponseEntity<Map<String, Object>> renameImage(
            @PathVariable String category,
            @PathVariable String filename,
            @RequestBody Map<String, String> request) {
        try {
            String newName = request.get("newName");
            if (newName == null || newName.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "新文件名不能为空"));
            }
            
            if (!isImageFile(newName)) {
                return ResponseEntity.badRequest().body(Map.of("error", "文件名必须包含有效的图片扩展名"));
            }
            
            File oldFile = new File(IMAGE_BASE_PATH + category + "/" + filename);
            File newFile = new File(IMAGE_BASE_PATH + category + "/" + newName);
            
            if (!oldFile.exists()) {
                return ResponseEntity.notFound().build();
            }
            
            if (newFile.exists()) {
                return ResponseEntity.badRequest().body(Map.of("error", "目标文件名已存在"));
            }
            
            boolean renamed = oldFile.renameTo(newFile);
            
            if (renamed) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("message", "图片重命名成功");
                result.put("oldName", filename);
                result.put("newName", newName);
                result.put("newPath", WEB_BASE_PATH + category + "/" + newName);
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.internalServerError().body(Map.of("error", "重命名失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of("error", "重命名操作失败：" + e.getMessage()));
        }
    }
    
    /**
     * 获取图片文件（处理中文文件名）
     */
    @GetMapping("/file/{category}/{filename:.+}")
    public ResponseEntity<org.springframework.core.io.Resource> getImageFile(
            @PathVariable String category,
            @PathVariable String filename) {
        try {
            // 解码文件名
            String decodedFilename = java.net.URLDecoder.decode(filename, "UTF-8");
            File imageFile = new File(IMAGE_BASE_PATH + category + "/" + decodedFilename);
            
            if (!imageFile.exists()) {
                return ResponseEntity.notFound().build();
            }
            
            org.springframework.core.io.Resource resource = new org.springframework.core.io.FileSystemResource(imageFile);
            
            // 设置正确的Content-Type
            String contentType = "image/jpeg"; // 默认
            if (decodedFilename.toLowerCase().endsWith(".png")) {
                contentType = "image/png";
            } else if (decodedFilename.toLowerCase().endsWith(".gif")) {
                contentType = "image/gif";
            } else if (decodedFilename.toLowerCase().endsWith(".webp")) {
                contentType = "image/webp";
            }
            
            return ResponseEntity.ok()
                    .contentType(org.springframework.http.MediaType.parseMediaType(contentType))
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 检查文件是否为图片
     */
    private boolean isImageFile(String filename) {
        if (filename == null) return false;
        String lowerCase = filename.toLowerCase();
        return lowerCase.endsWith(".jpg") || 
               lowerCase.endsWith(".jpeg") || 
               lowerCase.endsWith(".png") || 
               lowerCase.endsWith(".gif") || 
               lowerCase.endsWith(".webp");
    }
} 